package com.example.hello.service;

import com.example.hello.common.PageResult;
import com.example.hello.entity.Employee;
import com.example.hello.entity.EmployeeExperience;
import com.example.hello.mapper.EmployeeMapper;
import com.example.hello.mapper.EmployeeExperienceMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Base64;
import java.util.regex.Pattern;
import java.util.UUID;
import java.util.Arrays;

@Service
public class EmployeeService {

    private static final Logger log = LoggerFactory.getLogger(EmployeeService.class);

    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private EmployeeExperienceMapper experienceMapper;
    
    @Autowired
    private FileService fileService;  // 注入FileService
    
    private static final Pattern PHONE_PATTERN = Pattern.compile("^\\d{11}$");
    private static final long MAX_IMAGE_SIZE = 2 * 1024 * 1024; // 2MB

    /**
     * 分页查询员工列表
     */
    public PageResult<Employee> getEmployeeList(String name, String gender,
                                              LocalDate startDate, LocalDate endDate,
                                              Integer deptId,  // 添加部门ID参数
                                              Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Employee> employeePage = (Page<Employee>) employeeMapper.selectEmployeeList(
                name, gender, startDate, endDate, deptId);
        return new PageResult<>(employeePage.getTotal(), employeePage.getResult());
    }

    /**
     * 新增员工
     */
    @Transactional
    public Integer addEmployee(Employee employee) {
        // 参数校验
        validateEmployee(employee);
        
        // 设置默认密码和更新时间
        employee.setPassword("123456");
        employee.setUpdateTime(LocalDateTime.now());
        
        // 如果没有设置用户名，使用姓名拼音或手机号后4位
        if (employee.getUsername() == null || employee.getUsername().isEmpty()) {
            String phone = employee.getPhone();
            if (phone != null && phone.length() >= 4) {
                // 默认使用手机号后4位作为用户名
                String defaultUsername = phone.substring(phone.length() - 4);
                // 检查用户名是否已存在
                if (employeeMapper.selectByUsername(defaultUsername) != null) {
                    // 如果已存在，加上随机数
                    defaultUsername += "_" + UUID.randomUUID().toString().substring(0, 4);
                }
                employee.setUsername(defaultUsername);
            }
        }
        
        // 处理图片
        if (StringUtils.hasText(employee.getImage())) {
            validateAndProcessImage(employee);
        }
        
        // 保存员工信息
        employeeMapper.insert(employee);
        
        // 保存工作经历
        if (employee.getExperiences() != null) {
            for (EmployeeExperience exp : employee.getExperiences()) {
                exp.setEmpId(employee.getId());
                experienceMapper.insert(exp);
            }
        }
        
        return employee.getId();
    }

    /**
     * 修改员工信息
     */
    @Transactional
    public boolean updateEmployee(Integer id, Employee employee) {
        // 设置ID和更新时间
        employee.setId(id);
        employee.setUpdateTime(LocalDateTime.now());
        
        // 获取现有员工信息用于参数校验
        Employee existingEmployee = employeeMapper.selectById(id);
        if (existingEmployee == null) {
            return false;
        }
        
        // 参数校验
        validateEmployeeForUpdate(employee);
        
        // 处理图片
        if (StringUtils.hasText(employee.getImage())) {
            validateAndProcessImage(employee);
        }
        
        // 确保部门ID被正确设置
        log.info("更新员工部门: 员工ID={}, 旧部门ID={}, 新部门ID={}", 
                 id, existingEmployee.getDeptId(), employee.getDeptId());
        
        // 更新员工基本信息
        boolean success = employeeMapper.update(employee) > 0;
        
        // 更新工作经历
        if (success && employee.getExperiences() != null) {
            // 先删除现有的工作经历
            experienceMapper.deleteByEmpId(id);
            
            // 再添加新的工作经历
            for (EmployeeExperience exp : employee.getExperiences()) {
                exp.setEmpId(id);
                experienceMapper.insert(exp);
            }
        }
        
        return success;
    }

    /**
     * 删除员工
     */
    @Transactional
    public boolean deleteEmployee(Integer id) {
        // 先删除工作经历
        experienceMapper.deleteByEmpId(id);
        // 再删除员工
        return employeeMapper.deleteById(id) > 0;
    }

    /**
     * 查询员工详情
     */
    public Employee getEmployeeById(Integer id) {
        Employee employee = employeeMapper.selectById(id);
        if (employee != null) {
            // 查询工作经历
            List<EmployeeExperience> experiences = experienceMapper.selectByEmpId(id);
            employee.setExperiences(experiences);
        }
        return employee;
    }

    /**
     * 添加工作经历
     */
    @Transactional
    public boolean addExperience(Integer empId, EmployeeExperience experience) {
        experience.setEmpId(empId);
        return experienceMapper.insert(experience) > 0;
    }

    /**
     * 删除工作经历
     */
    @Transactional
    public boolean deleteExperience(Integer empId, Integer expId) {
        // 验证经历是否属于该员工
        List<EmployeeExperience> experiences = experienceMapper.selectByEmpId(empId);
        boolean belongs = experiences.stream()
                .anyMatch(exp -> exp.getId().equals(expId));
        if (!belongs) {
            return false;
        }
        return experienceMapper.deleteById(expId) > 0;
    }

    /**
     * 校验员工信息
     */
    private void validateEmployee(Employee employee) {
        // 校验姓名
        if (employee.getName() == null || 
            employee.getName().length() < 2 || 
            employee.getName().length() > 10) {
            throw new IllegalArgumentException("姓名长度必须在2-10个字符之间");
        }

        // 校验用户名
        if (employee.getUsername() == null || employee.getUsername().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        
        // 校验用户名唯一性
        Employee existingByUsername = employeeMapper.selectByUsername(employee.getUsername());
        if (existingByUsername != null) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 校验手机号
        if (!PHONE_PATTERN.matcher(employee.getPhone()).matches()) {
            throw new IllegalArgumentException("手机号必须为11位数字");
        }

        // 校验手机号唯一性
        Employee existingByPhone = employeeMapper.selectByPhone(employee.getPhone());
        if (existingByPhone != null) {
            throw new IllegalArgumentException("手机号已存在");
        }
    }

    /**
     * 校验员工更新信息
     */
    private void validateEmployeeForUpdate(Employee employee) {
        // 校验姓名
        if (employee.getName() != null && 
            (employee.getName().length() < 2 || employee.getName().length() > 10)) {
            throw new IllegalArgumentException("姓名长度必须在2-10个字符之间");
        }

        // 校验用户名
        if (employee.getUsername() != null) {
            // 检查用户名格式
            if (employee.getUsername().length() < 2 || employee.getUsername().length() > 20) {
                throw new IllegalArgumentException("用户名长度必须在2-20个字符之间");
            }
            
            // 检查用户名唯一性（排除自己）
            Employee existingByUsername = employeeMapper.selectByUsername(employee.getUsername());
            if (existingByUsername != null && !existingByUsername.getId().equals(employee.getId())) {
                throw new IllegalArgumentException("用户名已被其他员工使用");
            }
        }

        // 校验手机号
        if (employee.getPhone() != null) {
            if (!PHONE_PATTERN.matcher(employee.getPhone()).matches()) {
                throw new IllegalArgumentException("手机号必须为11位数字");
            }

            // 校验手机号唯一性
            Employee existingByPhone = employeeMapper.selectByPhone(employee.getPhone());
            if (existingByPhone != null && !existingByPhone.getId().equals(employee.getId())) {
                throw new IllegalArgumentException("手机号已存在");
            }
        }
    }

    /**
     * 校验并处理图片
     */
    private void validateAndProcessImage(Employee employee) {
        try {
            String base64Image = employee.getImage();
            if (base64Image == null || base64Image.trim().isEmpty()) {
                return;  // 如果没有图片，直接返回
            }

            // 如果已经是URL格式，说明图片未修改，直接返回
            if (base64Image.startsWith("http://") || base64Image.startsWith("https://")) {
                return;
            }

            // 处理可能的前缀问题
            if (base64Image.startsWith("data:")) {
                // 标准格式：...
                if (!base64Image.contains(";base64,")) {
                    throw new IllegalArgumentException("图片格式不正确，缺少base64标识");
                }
            } else {
                // 如果没有前缀，尝试添加默认的前缀
                base64Image = "data:image/jpeg;base64," + base64Image;
            }

            // 获取图片格式和数据
            String[] parts = base64Image.split(";base64,");
            if (parts.length != 2) {
                throw new IllegalArgumentException("图片数据格式不正确");
            }

            String imageType = parts[0].replace("data:", "");
            // 如果没有指定图片类型，默认使用jpeg
            if (!imageType.startsWith("image/")) {
                imageType = "image/jpeg";
            }

            // 支持的图片类型列表
            List<String> supportedTypes = Arrays.asList(
                "image/jpeg", "image/jpg", "image/png", "image/gif"
            );

            // 确保使用支持的图片类型
            if (!supportedTypes.contains(imageType)) {
                imageType = "image/jpeg"; // 默认转换为jpeg格式
            }

            // 解码Base64数据
            String base64Data = parts[1].trim()
                    .replace("\n", "")
                    .replace("\r", "")
                    .replace(" ", "+"); // 修复可能的空格问题

            byte[] imageBytes;
            try {
                imageBytes = Base64.getDecoder().decode(base64Data);
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败: {}", e.getMessage());
                throw new IllegalArgumentException("图片数据格式不正确，请确保是有效的Base64编码");
            }

            // 校验文件大小
            if (imageBytes.length > MAX_IMAGE_SIZE) {
                throw new IllegalArgumentException("图片大小不能超过2MB");
            }

            // 检查是否是有效的图片数据
            if (imageBytes.length < 100) { // 简单的图片有效性检查
                throw new IllegalArgumentException("无效的图片数据");
            }

            // 生成文件名
            String extension = "." + imageType.substring(imageType.lastIndexOf("/") + 1);
            String fileName = "employee_" + System.currentTimeMillis() + "_" + 
                            UUID.randomUUID().toString().substring(0, 8) + extension;

            // 上传图片并获取HTTPS URL
            String imageUrl = fileService.uploadBytes(imageBytes, fileName, imageType);
            employee.setImage(imageUrl);
            
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
            log.error("处理员工头像失败: {}", e.getMessage(), e);
            throw new RuntimeException("上传头像失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除员工
     * @param ids 员工ID列表
     * @return 是否全部删除成功
     */
    @Transactional
    public boolean deleteEmployees(List<Integer> ids) {
        try {
            log.info("批量删除员工: ids={}", ids);
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            
            // 先删除这些员工的工作经历
            for (Integer id : ids) {
                experienceMapper.deleteByEmpId(id);
            }
            
            // 再批量删除员工
            int rows = employeeMapper.deleteByIds(ids);
            return rows == ids.size();
        } catch (Exception e) {
            log.error("批量删除员工失败", e);
            throw e;
        }
    }
} 